//
//  NSString+Extension.m
//  MiaMind
//
//  Created by Vill on 2023/11/23.
//

#import "NSString+Extension.h"
#import<CommonCrypto/CommonDigest.h>
#import "UIImage+Extension.h"

@implementation NSString (Extension)

- (BOOL)strHasValue{
    if ([self isEqualToString:@""]) {
        return NO;
    }
    if ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return NO;
    }
    if (self == NULL || self == nil){
        return NO;
    }
    if ([self isKindOfClass:[NSNull class]]) {
        return NO;
    }
    if ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0){
        return NO;
    }
    if ([self isEqualToString:@"<null>"]) {
        return NO;
    }
    return YES;
}

//MD5
+(NSString *)stringToMD5:(NSString *)inputStr{
    const char *original_str = [inputStr UTF8String];
    unsigned char result[16];
    CC_MD5(original_str, (CC_LONG)strlen(original_str), result);
    NSMutableString* resultStr = [NSMutableString string];
    for (int i = 0; i <  16; i ++){
        [resultStr appendFormat:@"%02X",result[i]];
    }
    //转换为小写
    NSString *string = [resultStr lowercaseString];
    return string;
}

/**
 *  写入系统偏好
 *
 *  @param value 写入键值
 */
- (void)keySaveToNSDefaultsWithValue:(id)value{
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:self];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (id)backNSDefaultsKey{
    return  [[NSUserDefaults standardUserDefaults] objectForKey:self];
}

/**
 判断是否为合法邮箱地址
 */
+(BOOL)emailEvalunte:(NSString *)email{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

/**
 获取字符串的首字母, 缺省为#
 */
+ (NSString*)firstChar:(NSString *)string{
    if ((string == nil)|| (string == NULL) || ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) || [string isKindOfClass:[NSNull class]]) {
        return @"#";
    }
    NSMutableString *source = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);
    return [[source capitalizedString] substringToIndex:1];
}

// 读取本地JSON文件
+ (NSArray *)readLocalFileWithName:(NSString *)name{
    // 获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"geojson"];
    // 将文件数据化
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    // 对数据进行JSON格式化并返回字典形式
    return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
}

+ (NSString *)emojiFlagForISOCountryCode:(NSString *)code {
    int base = 127462 - 65;
    wchar_t bytes[2] = {
        base +[code characterAtIndex:0],
        base +[code characterAtIndex:1]
    };
    return [[NSString alloc] initWithBytes:bytes
                                    length:code.length *sizeof(wchar_t)
                                  encoding:NSUTF32LittleEndianStringEncoding];
}


/**
     富文本 文字+图片
     @param str 内容
     @param image 图片对象
     @param font  字体
     @param index  图片位置 0最前边  1最后边
     @return  字符串
 */
+ (NSMutableAttributedString *)getAttributedStr:(NSString *)str image:(UIImage *)image font:(UIFont *)font index:(NSUInteger)index{
    NSMutableAttributedString *contentAtt = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName : font}];
    NSTextAttachment *imageMent = [[NSTextAttachment alloc] init];
    imageMent.image = image;
    CGFloat paddingTop = font.lineHeight - font.pointSize;
    imageMent.bounds = CGRectMake(0, -paddingTop+3, font.lineHeight-3, font.lineHeight-3);
    NSAttributedString *imageAtt = [NSAttributedString attributedStringWithAttachment:imageMent];
    if (index == 0) {
        [contentAtt insertAttributedString:imageAtt atIndex:0];
    }else{
        [contentAtt appendAttributedString:imageAtt];
    }
    return contentAtt;
}

- (CGSize)sj_sizeWithFont:(UIFont *)font maxH:(CGFloat)maxH
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(MAXFLOAT, maxH);
    
    
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

- (CGSize)sj_sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW
{
    
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    
    
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

- (CGSize)sj_sizeWithFont:(UIFont *)font
{
    return [self sj_sizeWithFont:font maxW:MAXFLOAT];
}


// 将图片转换为 Base64 字符串
+ (NSString *)convertImageToBase64:(UIImage *)image{
    UIImage *resizeImg = [image ResizeScale:0.5];
    NSData *imageData = UIImageJPEGRepresentation(resizeImg, 0.5);
    NSString *base64String = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return base64String;
}

//+ (NSString *)convertImageToBase64String:(UIImage *)image{
//    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
//    NSUInteger chunkSize = 1024 * 1024; // 每个块的大小为 1MB
//    NSUInteger offset = 0;
//    NSMutableString *base64String = [NSMutableString string];
//    while (offset < imageData.length) {
//        NSRange range = NSMakeRange(offset, MIN(chunkSize, imageData.length - offset));
//        NSData *chunkData = [imageData subdataWithRange:range];
//        NSString *chunkString = [chunkData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
//        [base64String appendString:chunkString];
//        offset += chunkSize;
//    }
//    return base64String;
//}

// 获取当前UTC时间
+ (NSString *)getCurrentUTCDateString {
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd";
    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    NSString *currentUTCDateString = [dateFormatter stringFromDate:today];
    return currentUTCDateString;
}

// 是不是今天第一次登录
- (BOOL)isFirstLoginToday {
    NSString *currentUTCDateString = [NSString getCurrentUTCDateString];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL hasLoggedInToday = [userDefaults boolForKey:currentUTCDateString];
    if (!hasLoggedInToday) {
        [userDefaults setBool:YES forKey:currentUTCDateString];
        [userDefaults synchronize];
        return YES;
    } else {
        return NO;
    }
}

/**
    获取当前时间
    @param type   1:yyyyMMddHHmmss   2:yyyy-MM-dd HH:mm:ss
*/
+(NSString *)getCurrentDateTime:(NSInteger)type{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormaterr = [[NSDateFormatter alloc] init];
    NSString *str = type == 1 ? @"yyyyMMddHHmmss" : @"yyyy-MM-dd HH:mm:ss";
    [dateFormaterr setDateFormat:str];
    NSString *currentTime = [dateFormaterr stringFromDate:currentDate];
    return currentTime;
}


@end
